package levy.sum.chapter1.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class Server {

	private int port;

	public Server(int port) {
		this.port = port;
	}

	public static void main(String[] args) {
		new Server(9999).start();
	}

	public void start() {
		EventLoopGroup acceptor = new NioEventLoopGroup();
		EventLoopGroup worker = new NioEventLoopGroup();

		ServerBootstrap bootstrap = new ServerBootstrap();

		/** decide the connections queued */
		bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
		bootstrap.group(acceptor, worker);
		bootstrap.channel(NioServerSocketChannel.class);
		bootstrap.childHandler(new ServerInitHandler());

		try {
			Channel channel = bootstrap.bind(port).sync().channel();
			System.out.println("server startup in port:" + port);
			/** 同步等待关闭 */
			channel.closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
			System.out.println("server startup fail");
		} finally {
			acceptor.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
}
